package com.kitbox.hl.meshow.bpm.utils;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.lang.reflect.Field;
import java.util.*;

import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;


import com.goshine.sgcloud.platform.common.spring.PropertiesUtil;
import com.kitbox.hl.meshow.bpm.bean.BpmActorVo;
import com.kitbox.hl.meshow.bpm.bean.BpmNodeVo;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMNode;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.rpc.client.RPCServiceClient;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Attribute;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;





import java.io.*;
/**
 * xml文件解析
 * @author young
 *
 */



public class ClientUtils {

    String tenantId="";
    String tenantToken="";


    public static String client(String url,String nameSpace,String method,Object[] params){
        try {
            RPCServiceClient rpcClient = new RPCServiceClient();
            Options opt = new Options();
            opt.setTo(new EndpointReference(url)); //鏈嶅姟鍦板潃
            rpcClient.setOptions(opt);

            //租户ID
            String tenantId = PropertiesUtil.getProperty("bpm.tenantId");
            //令牌
            String tenantToken = PropertiesUtil.getProperty("bpm.tenantToken");

            rpcClient.addStringHeader(new QName(nameSpace, "TenantID"), tenantId );
            rpcClient.addStringHeader(new QName(nameSpace, "TenantToken"), tenantToken );

            OMElement element = rpcClient.invokeBlocking(new QName(nameSpace, method), params);
            Iterator iterator = element.getChildElements();
            OMNode omNode = (OMNode) iterator.next();
          return StringEscapeUtils.unescapeXml(omNode.toString()).replace("\n","");

        } catch (Exception e) {
            e.toString();
        }
        return null;
    }

    /**
     * 解析xml字符串返回一个 字符串
     *
     * @param xmlDoc
     * @return Map
     */
    public static String xmlElementsReturnString(String xmlDoc) {
        Map<String,String> map = new HashMap<String,String>();
        // 创建一个新的字符串
        StringReader read = new StringReader(xmlDoc);
        // 创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
        InputSource source = new InputSource(read);
        // 创建一个新的SAXBuilder
        SAXBuilder sb = new SAXBuilder();



        String result="";
        try {
            // 通过输入源构造一个Document
            org.jdom2.Document doc = sb.build(source);
            // 取的根元素
            org.jdom2.Element root = doc.getRootElement();
            if(null != root) {
                result = root.getText();
            }
        } catch (JDOMException e) {
            e.toString();
            System.out.println("出错");
        } catch (IOException e) {
            e.toString();
            System.out.println("出错");
        }
        read.close();
        return result;
    }

    /**
     * 解析xml字符串返回一个List<Object>
     *
     * @param xmlDoc
     * @return Map
     */
    public static  List<Map<String,String>> xmlElementsReturnList(String xmlDoc) {
        List<Map<String,String>> list = new ArrayList<Map<String,String>>();
        // 创建一个新的字符串
        StringReader read = new StringReader(xmlDoc);
        // 创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
        InputSource source = new InputSource(read);
        // 创建一个新的SAXBuilder
        SAXBuilder sb = new SAXBuilder();
        try {
            // 通过输入源构造一个Document
            org.jdom2.Document doc = sb.build(source);
            // 取的根元素
            org.jdom2.Element root = doc.getRootElement();
            // 得到根元素所有子元素的集合
            for (org.jdom2.Element ele : ((org.jdom2.Element) root).getChildren()){
                getChild(ele,list);
            }
        } catch (JDOMException e) {
            e.toString();
            System.out.println("出错");
        } catch (IOException e) {
            e.toString();
            System.out.println("出错");
        }
        read.close();
        return list;
    }

    public static void getChild(org.jdom2.Element ele, List<Map<String,String>> list) {
        List<org.jdom2.Element> children = ele.getChildren();

        if (!children.isEmpty()) {
            Map<String,String> map=new HashMap<String,String>();
            for (org.jdom2.Element e : children) {
                if(StringUtils.isNotBlank(e.getText())) {
                    map.put(e.getName(), e.getText());
                }
                getChild(e, list);
            }
            if(!map.isEmpty()) {
                list.add(map);
            }
        }
    }

    public static org.jdom2.Document str2XML(String string) throws Exception {

        SAXBuilder buider = new SAXBuilder();

        org.jdom2.Document document = buider.build(new StringReader(string));

        return document;

    }


    /**
     * 解析xml字符串返回一个List<Object>
     *
     * @param xmlDoc
     * @return Map
     */
   /* public static  List<LinkedHashMap<String,String>> xmlElementsReturnList1(String xmlDoc) {
        List<LinkedHashMap<String,String>> list = new ArrayList<LinkedHashMap<String,String>>();
        // 创建一个新的字符串
        StringReader read = new StringReader(xmlDoc);
        // 创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
        InputSource source = new InputSource(read);
        // 创建一个新的SAXBuilder
        SAXBuilder sb = new SAXBuilder();
        try {
            // 通过输入源构造一个Document
           // Document doc = sb.build(source);
            Document doc = (Document) DocumentHelper.parseText(xmlDoc);
            // 取的根元素
            Element root = doc.getRootElement();

            // 得到根元素所有子元素的集合
            for (Element ele : ((Element) root).getChildren()){
                getChild1(ele,list);
            }
        } catch (Exception e) {
            e.toString();
            System.out.println("出错");
        }
        read.close();
        return list;
    }

    public static void getChild1(Element ele, List<LinkedHashMap<String,String>> list) {
        List<Element> children = ele.getChildren();

        if (!children.isEmpty()) {
            LinkedHashMap<String,String> map=new LinkedHashMap<String,String>();
            for (Element e : children) {

                if("UserTask".equals(e.getDocument())){
                    System.out.print(e.getDocument().getRootElement().getName());
                }
                if(StringUtils.isNoneBlank(e.getAttributeValue("name"))){
                    System.out.print(e.getAttributeValue("id"));
                    System.out.print(e.getAttributeValue("name"));
                    map.put(e.getAttributeValue("name"), e.getAttributeValue("name"));

                }
                //if(StringUtils.isNotBlank(e.getText()) && ("id".equals(e.getName()) || "type".equals(e.getName()) || "name".equals(e.getName()))){
                    map.put(e.getName(), e.getText());
               // }
                getChild1(e, list);
            }

            if(!map.isEmpty())
                list.add(map);
        }
    }
*/
public static  List<BpmNodeVo> XmlExam(String xmlDoc) throws DocumentException {
    if(StringUtils.isNotBlank(xmlDoc)){
        org.dom4j.Document document = DocumentHelper.parseText(xmlDoc);
        org.dom4j.Element ele = document.getRootElement();
        List<Map<String,String>> list =new ArrayList();
        parserNode(ele,list);

        Map<String,String> m=new HashMap();
        m.put("split","");//为了保证最后节点  取数正常
        list.add(m);

        if(null!=list && list.size()>0){
            BpmNodeVo node= null;
            BpmActorVo v= null;
            List<BpmActorVo> vList=null;
            List<BpmNodeVo> nList=new ArrayList();
            for(Map<String,String> map:list) {
                for (Map.Entry<String, String> entry : map.entrySet()) {
                    if("split".equals(entry.getKey())){
                        if(null!=vList && vList.size()>0){
                            node.setBpmActorVoList(vList);
                            nList.add(node);
                        }
                        node=new BpmNodeVo();
                        node.setNodeId(entry.getValue());
                        v=new BpmActorVo();
                        vList =new ArrayList();
                    }

                    if(null!=v){
                        if("id".equals(entry.getKey())) {
                            v.setId(entry.getValue());
                        }
                        if("name".equals(entry.getKey())) {
                            v.setName(entry.getValue());
                        }
                        if("type".equals(entry.getKey())) {
                            v.setType(entry.getValue());
                        }

                        if(StringUtils.isNotBlank(v.getId()) && StringUtils.isNotBlank(v.getName()) && StringUtils.isNotBlank(v.getType())){
                            vList.add(v);
                            v=new BpmActorVo();
                        }
                    }

                    System.out.println("key："+entry.getKey()+"   vaule："+entry.getValue());
                }
            }
            return nList;
        }
        return null;
    }
    return null;

}
    public static void parserNode(org.dom4j.Element ele,List<Map<String,String>> list){


        if("userTask".equals(ele.getName())){
            //System.out.println(ele.getName()+":"+ele.getText().trim());

            List<Attribute> attrList = ele.attributes();
            for(Attribute attr : attrList){
                Map<String,String> map=new HashMap();
                //每循环一次，解析此节点的一个【属性=值】，没有则输出空
                if("id".equals(attr.getName())) {
                    map.put("split",attr.getValue());
                    list.add(map);
                    //System.out.println(attr.getValue());
                }
                if("name".equals(attr.getName())) {
                   // System.out.println(attr.getValue());
                }
            }
        }
        if("id".equals(ele.getName()) || "name".equals(ele.getName()) || "type".equals(ele.getName())){
            Map<String,String> map=new HashMap();
            //System.out.println(ele.getName()+":"+ele.getText().trim());
            map.put(ele.getName(),ele.getText().trim());
            list.add(map);

        }

        List<org.dom4j.Element> eleList = ele.elements();
        //递归遍历父节点下的所有子节点
        for(org.dom4j.Element e : eleList){
            parserNode(e,list);
        }
    }

}
